<?php

namespace zhtfrontend\modules\teachergrowth\controllers;

use common\components\helpers\Fun;
use common\components\helpers\Util;
use common\models\datas\Customer;
use common\models\datas\Student;
use frontend\models\datas\OrdersItems;
use yii\helpers\ArrayHelper;
use zhtfrontend\models\datas\ClassManage;
use zhtfrontend\models\datas\ClassManageAttribute;
use zhtfrontend\models\datas\ClassManageGoods;
use zhtfrontend\models\datas\ClassManageTeacher;
use zhtfrontend\models\datas\ClassManageTime;
use zhtfrontend\models\datas\Classroom;
use zhtfrontend\models\datas\ClassroomAttr;
use zhtfrontend\models\datas\ClassStudent;
use zhtfrontend\models\datas\Orders;
use zhtfrontend\models\datas\OrdersItemsRelation;
use zhtfrontend\models\datas\Teacher;
use zhtfrontend\modules\teachergrowth\components\rest\ActiveController;
use yii\web\Response;

class OrderController extends ActiveController

{
    private $_config;
    public $modelClass = 'zhtfrontend\models\datas\ClassManage';

    public $serializer = [
        'class' => 'zhtfrontend\modules\teachergrowth\components\rest\Serializer',
        'collectionEnvelope' => 'items',
    ];

    public function behaviors()
    {
        $behaviors = parent::behaviors();
        $behaviors['contentNegotiator']['formats']['text/html'] = Response::FORMAT_JSON;
        return $behaviors;
    }

    public function actions()
    {
        $actions = parent::actions();
        unset($actions['index'], $actions['create'], $actions['update'], $actions['delete'], $actions['view']);
        return $actions;
    }


    public function actionCourselist(){
        //只查找未开班的课程
        $data = \Yii::$app->request->post();
        $teacher_id=ArrayHelper::keyExists('teacher_id', $data) ? $data['teacher_id'] : '';
        $class_manage_teacher=ClassManageTeacher::find()->where(['teacher_id'=>$teacher_id])->asArray()->all();
        if (empty($class_manage_teacher)){
            return ['statusCode' => 0, 'message' => 'error', 'result' => '暂时没有课程'];
        }else{
            $course=[];
            $class_ids = ArrayHelper::getColumn($class_manage_teacher, 'class_id');
            $class_manage=ClassManage::find()->where(['class_id'=>$class_ids,'status'=>[0]])->asArray()->all();//这个地方只查找未开班的课程
            if(empty($class_manage)){
                return ['statusCode' => 0, 'message' => 'error', 'result' => '没有未开班课程'];
            }
            foreach ($class_manage as $k=>$v){
                switch ($v['status']){
                    case 0:
                        $v['status']='未开班';break;
                    case 1:
                        $v['status']='已开班';break;
                    case 2:
                        $v['status']='已结束';break;
                };
                $class_manage_attribute=ClassManageAttribute::find()->where(['class_id'=>$v['class_id']])->one();
                $class_manage_time=ClassManageTime::find()->where(['class_id'=>$v['class_id']])->one();
                //需要查找学生的预约情况
                $goods_id=ClassManageGoods::find()->where(['class_id'=>$v['class_id']])->all();
                $goods_id_array=ArrayHelper::getColumn($goods_id, 'goods_id');//找到当前课程对应的goods_id,然后去找当前的goods_id下面的订单信息
                //$orders=Orders::find()->where(['goods_id'=>$goods_id_array,'status'=>[0,1,4]])->all();
                $orders=OrdersItems::find()->joinWith('orders')->where(['dmd_orders.status'=>[0,1,4],'goods_id'=>$goods_id_array])->all();
                $orders_count=count($orders);
                if ($class_manage_attribute->max_number==$orders_count){
                    $appoint_status="已报满";
                    $icon='icon-personal-full';
                    $statebox="dmd-course-full-box";
                }else{
                    $appoint_status="预约中";
                    $icon='icon-order-count';
                    $statebox="dmd-course-unfull-box";
                }
                if (isset($class_manage_time->class_day)){
                    switch ($class_manage_time->class_day){
                        case 1:
                            $class_manage_time->class_day="周一";break;
                        case 2:
                            $class_manage_time->class_day="周二";break;
                        case 3:
                            $class_manage_time->class_day="周三";break;
                        case 4:
                            $class_manage_time->class_day="周四";break;
                        case 5:
                            $class_manage_time->class_day="周五";break;
                        case 6:
                            $class_manage_time->class_day="周六";break;
                        case 7:
                            $class_manage_time->class_day="周日";break;
                    }
                }
                $course[$v['class_id']]=[
                    'id'=>$v['class_id'],
                    'class_id'=>$v['class_id'],
                    'max_number'=>isset($class_manage_attribute->max_number)?$class_manage_attribute->max_number:'',
                    'course_name'=>isset($class_manage_attribute->course)?$class_manage_attribute->course:'',
                    'class_time_day'=>isset($class_manage_time->class_day)?$class_manage_time->class_day:'',
                    'class_time_start'=>isset($class_manage_time->start_time)?$class_manage_time->start_time:'',
                    'class_time_end'=>isset($class_manage_time->end_time)?$class_manage_time->end_time:'',
                    'status'=>$v['status'],
                    'appoint_number'=>$orders_count,
                    'appoint_status'=>$appoint_status,
                    'icon'=>$icon,
                    'stateBox'=>$statebox,
                ];
            }
            $items=[
                'course_info'=>$course,
                'course_counts'=>count($course)
            ];
            return ['statusCode' => 200, 'message' => 'success', 'items' => $items];
        }

    }

    public function actionStudentlist(){
        $data = \Yii::$app->request->post();
        $class_id=ArrayHelper::keyExists('class_id', $data) ? $data['class_id'] : '';
        //查看班里的人数
        $total_number=ClassManageAttribute::find()->where(['class_id'=>$class_id])->one();
       //需要查找学生的预约情况
        $goods_id=ClassManageGoods::find()->where(['class_id'=>$class_id])->all();
        $goods_id_array=ArrayHelper::getColumn($goods_id, 'goods_id');
        //查找预约人数
        $appoint_number=OrdersItems::find()->joinWith('orders')->where(['dmd_orders.status'=>[0,1,4],'goods_id'=>$goods_id_array])->all();
        $appoint_number_count=count($appoint_number);
        //查找入班人数
        $entry_number=ClassStudent::find()->where(['class_manage_id'=>$class_id])->all();
        $entry_number_count=count($entry_number);
        //查找未缴费人数
        $nomoney_number=OrdersItems::find()->joinWith('orders')->where(['dmd_orders.status'=>[0,1],'dmd_orders.pay_status'=>[0],'goods_id'=>$goods_id_array])->all();
        $nomoney_number_conut=count($nomoney_number);
        //下面是学生列表
        $order_items=OrdersItems::find()->joinWith('orders')->where(['goods_id'=>$goods_id_array])->asArray()->all();

        $student_info=[];
        foreach ($order_items as $key=>$val){
            $student=Student::find()->where(['id'=>$val['student_id']])->one();
            $customer=Customer::find()->where(['id'=>$student->customer_id])->one();
            //下面是判断班级的状态
            $class_status=[];
            if($val['orders']['status']==0 || $val['orders']['status']==1){
                if ($val['orders']['pay_status']==0){//已经预约状态
                    $class_status=[
                        'order_state'=>'dmd-student-ordered-box',
                        'state'=>'已预约',
                        'date_box'=>'dmd-ordered-date',
                        'state_icon'=>'icon-ordered',
                    ];
                }elseif ($val['orders']['pay_status']==1){//交钱了就是已经入班状态
                    $class_status=[
                        'order_state'=>'dmd-student-handled-box',
                        'state'=>'已办理入学',
                        'date_box'=>'dmd-ordered-date',
                        'state_icon'=>'icon-handled',
                    ];
                }else{
                    $class_status=[//如果是5或者是其他的就是关闭状态
                        'order_state'=>'dmd-student-closed-box',
                        'state'=>'过期已关闭',
                        'date_box'=>'dmd-ordered-date',
                        'state_icon'=>'icon-closed',
                    ];
                }
            }elseif($val['orders']['status']==2){//如果是2的话直接是已关闭状态
                $class_status=[
                    'order_state'=>'dmd-student-closed-box',
                    'state'=>'过期已关闭',
                    'date_box'=>'dmd-ordered-date',
                    'state_icon'=>'icon-closed',
                ];
            }else{
                $class_status=[
                    'order_state'=>'dmd-student-closed-box',
                    'state'=>'已退货',
                    'date_box'=>'dmd-ordered-date',
                    'state_icon'=>'icon-closed',
                ];
            }
            if ($student->sex==0){
                $sexIcon='icon-female';
                $sexiconBox='dmd-female-icon';
            }else{
                $sexIcon='icon-male';
                $sexiconBox='dmd-male-icon';
            }

            $student_info[$key]=[
                'id'=>isset($student->id) ? $student->id: '',
                'student_name'=>isset($student->name) ?$student->name:'',
                'student_img'=>isset($student->img) ?$student->img:'',
                'student_sex'=>isset($student->sex) ?$student->sex:'',
                'sex_icon'=>$sexIcon,
                'sex_iconbox'=>$sexiconBox,
                'telephone'=>isset($customer->mobile)?$customer->mobile:'',
                'class_status'=>$class_status,
                'appoint_time'=>date('Y-m-d',$val['created_at']),
            ];
        }
        $items=[
            'total_number'=>isset($total_number->max_number)?$total_number->max_number:'',
            'appoint_number_count'=>$appoint_number_count,
            'entry_number_count'=>$entry_number_count,
            'nomoney_number_conut'=>$nomoney_number_conut,
            'student_info'=>$student_info,


        ];
        return ['statusCode' => 200, 'message' => 'success', 'items' => $items];

    }

    //下面是强行开班
    public function actionForceopen(){
        $data = \Yii::$app->request->post();
        $post = \Yii::$app->request->post();
        $class_id=ArrayHelper::keyExists('class_id', $data) ? $data['class_id'] : '';
        $cycle=1;//上课周期，现在是不能选的，那么我就给他写死吧
        $start_times=ArrayHelper::keyExists('start_time', $data) ? $data['start_time'] : '';
        if (empty($class_id)){
            return ['statusCode' => 0, 'message' => 'error', 'result' => '没有信息1'];
        }else{
            $model = ClassManage::findOne($class_id);
            if ($model === null) {
                return ['statusCode' => 0, 'message' => 'error', 'result' => '没有信息2'];
            }
            //下面是验证开班时间了
            if (!empty($model->status)) {
                $date = (int)date("N", \Yii::$app->formatter->asTimestamp($start_times));
                $time = \Yii::$app->formatter->asTimestamp($start_times);
                $nowtime = strtotime(date('Y-m-d'));
                $class_day = isset($this->arrangeMent->classroom_attr_id) ? $this->arrangeMent->classroom_attr_id : '';
                $classDays = ClassManageTime::find()->select('class_day')->where(['class_id' => $this->class_id])->column();
                if ($time < $nowtime) {
                    return ['statusCode' => 0, 'message' => 'error', 'result' => '开课时间不能小于当前时间'];
                }
                if ($class_day == '') {
                    return ['statusCode' => 0, 'message' => 'error', 'result' => '排课表中无对应信息'];
                }
                $classroom_attr_ids = explode(',', $class_day);
                $weeks = ClassroomAttr::find()->select('classday')->where(['id' => $classroom_attr_ids])->column();
                if (!in_array($date, $weeks)) {
                    return ['statusCode' => 0, 'message' => 'error', 'result' => '必须与上课星期相同'];
                }
                if (!in_array($date, $classDays)) {
                    return ['statusCode' => 0, 'message' => 'error', 'result' => '必须与上课星期相同'];
                }
            }

            $studentCount = ClassStudent::find()->where(['class_manage_id' => $class_id, 'status' => 0])->count();
            if ($studentCount == 0) {
                return ['statusCode' => 0, 'message' => 'error', 'result' => '没有学生不能开班'];
            }
            $goods_time_array = ClassManageTime::find()->where(['class_id' => $class_id])->orderBy('class_day,start_time ASC')->asArray()->all();
            if (empty($goods_time_array)) {
                return ['statusCode' => 0, 'message' => 'error', 'result' => '信息不存在'];
            }
            $classattr = ClassManageAttribute::find()->where(['class_id' => $class_id])->one();
            if ($classattr == null) {
                return ['statusCode' => 0, 'message' => 'error', 'result' => '信息不存在'];
            }
            $class_manage_attr = ClassManageAttribute::findOne(['class_id' => $class_id]);
            $class_manage_time = ClassManageTime::findOne(['class_id' => $class_id]);

            //下面是教室的值
            if ($class_manage_attr->room_type == 1) {
                $room_type = 1;
                $classrooms = Classroom::find()->where(['classroom_group_id' => $class_manage_attr->room_group_id])->all();
                $classroom = ArrayHelper::map($classrooms, 'id', 'name');
                //排除共享组里面该时段被占用的教室str_replace
                $classroom = [];
                foreach ($classrooms as $k => $v) {
                    $classroom_attr_id_no = ClassroomAttr::find()->select('id')
                        ->where(['classroom_id'=>$v->id,'classday'=>$class_manage_time->class_day])
                        ->andWhere(['<=','end_time',str_replace(':','',$class_manage_time->start_time)])
                        ->andWhere(['>=','start_time',str_replace(':','',$class_manage_time->end_time)])
                        ->column();
                    $classroom_attr_id = ClassroomAttr::find()->select('id')
                        ->where(['classroom_id'=>$v->id,'classday'=>$class_manage_time->class_day])
                        ->andWhere(['not in','id',$classroom_attr_id_no])
                        ->column();
                    $class_ids = ClassManageTime::find()->select('class_id')->where(['classroom_attr_id'=>$classroom_attr_id])->column();
                    $class_manage = ClassManage::find()->where(['class_id'=>$class_ids,'status'=>1])->all();
                    if(empty($class_manage)){
                        $classroom[$v->id] = $v->name .'-'.$v->room_number;
                    }
                }
            } else {
                $room_type = 0;
                $classroom = [];
            }
            //获取班主任
            $classTeacher = ClassManageTeacher::find()->where(['class_id' => $class_id])->one();
            $teacher = Teacher::findOne($classTeacher->teacher_id);
            $model->headmaster = isset($teacher) ? $teacher->parent_id : 0;

            //查找管理次班级的所有商品
            $goodsIds = ClassManageGoods::find()->select('goods_id')->where(['class_id' => $class_id])->column();
            $count = OrdersItemsRelation::find()->where(['goods_id' => $goodsIds])->max('lesson');

            //下面是保存吧
            $transaction = \Yii::$app->db->beginTransaction();
            try {
                if (isset($post['ClassManage']['classroom_id']) && !empty($post['ClassManage']['classroom_id'])) {
                    $classroom = Classroom::findOne($post['ClassManage']['classroom_id']);
                    $class_manage_attr->room_id = $classroom->id;
                    $class_manage_attr->classroom_name = $classroom->name;
                    $class_manage_attr->classroom_number = $classroom->room_number;
                    $class_manage_attr->room_group_id = '';
                    $class_manage_attr->room_type = 0;
                    $class_manage_attr->save(false);
                }
                if ($model->status == 1) {
                    $start_time = 0;
                    $end_time = 0;
                    $diff = 0;
                    $times_week = count($goods_time_array); //每周上课次数
                    //插入class_lesson
                    $startweek = (int)date("N", \Yii::$app->formatter->asTimestamp($start_times));
                    $j = 1;
                    $first_week_times = 0;

                    $insert_array = [];
                    $length = $flag = $count + $times_week;
                    $array = $this->getClassLessonArray($length, $goods_time_array);
                    $index = 0;
                    $c = 0;
                    for ($m = 0; $m < $length; $m++) {
                        if ($m == 0) {//第一周
                            foreach ($goods_time_array as $k => $v) {
                                if ($startweek > $v['class_day']) {
                                    unset($array[$k]);
                                    $flag--;
                                    $index++;
                                } else {
                                    $s = explode(':', $array[$index + $diff]['start_time']);
                                    if ($j == 1) {
                                        $start_time = strtotime($start_times) + (int)$s[0] * 60 * 60 + (int)$s[1] * 60; //开始上课时间
                                    }
                                    $insert_array[$j]['class_id'] = $class_id;
                                    $insert_array[$j]['class_date'] = strtotime($start_times) + ($array[$index + $diff]['class_day'] - $startweek) * 60 * 60 * 24 + (int)$s[0] * 60 * 60 + (int)$s[1] * 60;
                                    $insert_array[$j]['start_time'] = str_replace(':', '', $array[$index + $diff]['start_time']);
                                    $insert_array[$j]['end_time'] = str_replace(':', '', $array[$index + $diff]['end_time']);
                                    $insert_array[$j]['lesson'] = $j;
                                    $insert_array[$j]['title'] = isset($classattr->course) ? $classattr->course : '';
                                    $insert_array[$j]['status'] = 0;
                                    $insert_array[$j]['ovo'] = isset($classattr->teacher_form) ? $classattr->teacher_form : '';

                                    if ($j == $count) {
                                        $dates = strtotime($start_times) + ($array[$index + $diff]['class_day'] - $startweek) * 60 * 60 * 24;
                                        $htime = floor($insert_array[$j]['end_time'] / 100) * 3600 + (int)substr($insert_array[$j]['end_time'], 2) * 60;
                                        $end_time = $dates + $htime;
                                    }
                                    $j++;
                                    $first_week_times++;
                                    $diff++;
                                }
                            }
                        } elseif ($m >= $times_week) {
                            if ($count < $flag) {//其他周并且还未将添加的剔除干净
                                array_pop($array);
                                $flag--;
                            } else {
                                $e = explode(':', $array[$j - 1 + $index]['start_time']);
                                $end = explode(':', $array[$j - 1 + $index]['end_time']);
                                $aaa = floor(($j - $first_week_times) % $times_week);
                                $cycle_s = 0;
                                if($cycle > 0){
                                    $cycle_s = $cycle + $c;
                                    $c++;
                                }

                                if ($aaa == 0) {
                                    $time = strtotime($start_times) + ((floor(($j - $first_week_times) / $times_week)+$cycle_s) * 7 + $array[$j - 1 + $index]['class_day'] - $startweek) * 60 * 60 * 24 + (int)$e[0] * 60 * 60 + (int)$e[1] * 60;
                                    $en_time = strtotime($start_times) + (floor(($j - $first_week_times) / $times_week) * 7 + $array[$j - 1 + $index]['class_day'] - $startweek) * 60 * 60 * 24 + (int)$end[0] * 60 * 60 + (int)$end[1] * 60 ;
                                } else {
                                    $time = strtotime($start_times) + ((floor(($j - $first_week_times) / $times_week + 1)+$cycle_s) * 7 + $array[$j - 1 + $index]['class_day'] - $startweek) * 60 * 60 * 24 + (int)$e[0] * 60 * 60 + (int)$e[1] * 60;
                                    $en_time = strtotime($start_times) + (floor(($j - $first_week_times) / $times_week + 1) * 7 + $array[$j - 1 + $index]['class_day'] - $startweek) * 60 * 60 * 24 + (int)$end[0] * 60 * 60 + (int)$end[1] * 60;
                                }
                                if ($j == $count) {
                                    $end_time = $en_time;
                                }
                                $insert_array[$j]['class_id'] = $class_id;
                                $insert_array[$j]['class_date'] = $time;
                                $insert_array[$j]['start_time'] = str_replace(':', '', $array[$j - 1 + $index]['start_time']);
                                $insert_array[$j]['end_time'] = str_replace(':', '', $array[$j - 1 + $index]['end_time']);
                                $insert_array[$j]['lesson'] = $j;
                                $insert_array[$j]['title'] = isset($classattr->course) ? $classattr->course : '';
                                $insert_array[$j]['status'] = 0;
                                $insert_array[$j]['ovo'] = isset($classattr->teacher_form) ? $classattr->teacher_form : '';
                                $j++;
                            }

                        }
                    }
                    $model->start_time = $start_time;
                    $model->end_time = $end_time;
                    $model->save(false);
                    Fun::getSiteDb()->createCommand()->batchInsert('{{%class_lesson}}', ['class_id', 'class_date', 'start_time', 'end_time', 'lesson', 'title', 'status', 'ovo'], $insert_array)->execute();
                    $transaction->commit();
                    return ['statusCode' => 200, 'message' => 'error', 'items' => '开班成功'];
                }else{
                    $model->status=1;
                    $model->start_time=strtotime($start_times);
                    $model->save();
                    return ['statusCode' => 200, 'message' => 'error', 'result' => '开班成功'];
                }
            } catch (\Exception $e) {
                $transaction->rollBack();
                return ['statusCode' => 0, 'message' => 'error', 'result' => '开班失败12'];
            }
            $weekstr = '';
            foreach($goods_time_array as $week){
                $weekstr .= Util::getWeek($week['class_day']).' ';
            }
            return ['statusCode' => 200, 'message' => 'error', 'items' => '开班成功'];
        }
    }

    public function getClassLessonArray($length, $goods_time_array)
    {
        $array = [];
        $ids_length = count($goods_time_array);
        for ($i = 0; $i < $length; $i++) {
            if (empty($array)) {
                $array[] = $goods_time_array[0];
            } else {
                $array[] = $goods_time_array[$i % $ids_length];
            }
        }
        return $array;
    }


}